{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 撰写人：姚晓琪\n",
    "* 日期：2020年10月31日"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 总结字典和集合的用法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1.字典"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.1字典操作\n",
    "字典是一种key_value的数字类型，又叫做键/值对。\n",
    "* 特性，字典是无序的，但是key是唯一的，不变性的，如果重复最后的一个键/值对会替换前面的，值不需要唯一的。\n",
    "* 字典的值可以取任何数据类型，但键必须是不可变的，如：字符串、数字或数组。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'name': '姚嘻嘻', 'identity': '19网新学生', 'teacher': '游鸽'}"
      ]
     },
     "execution_count": 55,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dict = {\n",
    "    \"name\":\"姚晓琪\",       # name是key，“姚晓琪”是value\n",
    "    \"identity\":\"19网新学生\",\n",
    "    \"teacher\":\"游鸽\",\n",
    "    \"name\":\"姚嘻嘻\"\n",
    "}\n",
    "dict"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.2 访问字典里的值\n",
    "字典里的值的访问用：字典名称[key]。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'姚嘻嘻'"
      ]
     },
     "execution_count": 56,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dict[\"name\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.3 字典的增加\n",
    "向字典添加新内容的方法是增加新的键/值对，修改或删除已有键/值对。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'name': '姚嘻嘻', 'identity': '19网新学生', 'teacher': '游鸽', 'school': '中山大学南方学院'}"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dict[\"school\"] = \"中山大学南方学院\"      # 增加新的键/值对\n",
    "dict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'name': '姚嘻嘻', 'identity': '19网新学生', 'teacher': '许智超', 'school': '中山大学南方学院'}"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dict[\"teacher\"] = \"许智超\"     # 修改已有键/值对\n",
    "dict"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.4 字典的删除\n",
    "能删单一的元素也能清空字典，清空只需一项操作。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'identity': '19网新学生', 'teacher': '许智超', 'school': '中山大学南方学院'}"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "del dict['name']\n",
    "dict"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.5 字典的内置函数与方法\n",
    "* cmp(dict1,dict2):比较两个字典元素(python3中删除了该函数)\n",
    "* len(dict):计算字典元素个数，即键的总数\n",
    "* str(dict):输出字典课打印的字符串表示\n",
    "* type(variable):返回输入的变量类型，如果变量是字典就返回字典类型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dict1 = {\n",
    "    \"name1\":\"本特利\",\n",
    "    \"name2\":\"威廉\"\n",
    "}\n",
    "len(dict1)     # 计算字典元素个数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"{'name1': '本特利', 'name2': '威廉'}\""
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "str(dict1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'{'"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "str(dict1)[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.6 字典的嵌套"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'威廉': {'年龄': '5岁', '星座': '巨蟹座', '国籍': '韩国'},\n",
       " '本特利': {'年龄': '4岁', '星座': '天蝎座', '国籍': '韩国'}}"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "FamousDict = {\n",
    "    \"威廉\":{\n",
    "        \"年龄\":\"5岁\",\n",
    "        \"星座\":\"巨蟹座\",\n",
    "        \"国籍\":\"韩国\"\n",
    "    },\n",
    "    \"本特利\":{\n",
    "        \"年龄\":\"4岁\",\n",
    "        \"星座\":\"天蝎座\",\n",
    "        \"国籍\":\"韩国\"\n",
    "    }\n",
    "}\n",
    "FamousDict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'巨蟹座'"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "FamousDict[\"威廉\"][\"星座\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.7 迭代处理字典"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请输入一个只带字母的字符串jkluiofahe\n",
      "a is found 1 time(s)\n",
      "e is found 1 time(s)\n",
      "i is found 1 time(s)\n",
      "o is found 1 time(s)\n",
      "u is found 1 time(s)\n"
     ]
    }
   ],
   "source": [
    "voles = [\"a\",\"e\",\"i\",\"o\",\"u\"]\n",
    "word = input(\"请输入一个只带字母的字符串\")\n",
    "found = {}\n",
    "found[\"a\"] = 0\n",
    "found[\"e\"] = 0\n",
    "found[\"i\"] = 0\n",
    "found[\"o\"] = 0\n",
    "found[\"u\"] = 0\n",
    "for i in word:\n",
    "    if i in voles:\n",
    "        found[i] +=1\n",
    "for k,v in sorted(found.items()):\n",
    "    print(k,\"is found\",v,\"time(s)\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.8 字典中 in和not in的用法\n",
    "可以用in操作符来检查一个字典中是否存在这个键，这样可以有效的避免字典取值时出现的keyerror"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'apples': 10, 'bananas': 1}\n"
     ]
    }
   ],
   "source": [
    "fruits = {}\n",
    "fruits[\"apples\"] = 10\n",
    "if \"bananas\" in fruits:\n",
    "    True\n",
    "elif \"bananas\" not in fruits:\n",
    "    fruits[\"bananas\"] = 0\n",
    "fruits[\"bananas\"] +=1\n",
    "print(fruits)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.9 字典中的setdefault()方法\n",
    "setdefault(key,value)的表达方式\n",
    "setdefault是完成2行if/not in语句所做的工作，不过是用一行代码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'apples': 10, 'bananas': 1}\n"
     ]
    }
   ],
   "source": [
    "fruits = {}\n",
    "fruits[\"apples\"] = 10\n",
    "fruits.setdefault(\"bananas\",0)\n",
    "fruits[\"bananas\"]+=1\n",
    "print(fruits)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. 集合\n",
    "集合不允许有重复，集合是用大括号包围着，集合中只有逗号，绝对没有冒号"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.1 集合的创建"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a', 'd', 'e', 'i', 't'}"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = {\"a\",\"e\",\"e\",\"t\",\"i\",\"d\"}      # 相同元素会自动合并\n",
    "a"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.2 集合的快速创建\n",
    "集合中用set()函数可以快速创建一个集合（例如一个字符串）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'c', 'h', 'l', 'o', 's'}"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = set(\"school\")\n",
    "a"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.3 集合和列表的转换\n",
    "利用sorted()与list()函数将一个集合转化为一个有序的列表"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['c', 'h', 'l', 'o', 's']"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "b = sorted(list(a))\n",
    "b"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.4 集合的合并\n",
    "union合并集合"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'c', 'e', 'h', 'l', 'o', 's'}"
      ]
     },
     "execution_count": 50,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "word = \"hello\"\n",
    "b = a.union(set(word))\n",
    "b"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.5 分辨是否共有元素\n",
    "difference()告诉你哪些不是共有的元素"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'c', 's'}"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "b = a.difference(set(word))\n",
    "b"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.6 查询共同元素\n",
    "intersection()报告共同对象"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'h', 'l', 'o'}"
      ]
     },
     "execution_count": 53,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "b = a.intersection(set(word))\n",
    "b"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 猜数字练习"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "hide_hard = random.randint(1,100)\n",
    "count = 0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请输入一个数字67\n",
      "你猜的数字太小了\n",
      "请输入一个数字78\n",
      "你猜的数字太大了\n",
      "请输入一个数字68\n",
      "你猜的数字太小了\n",
      "请输入一个数字69\n",
      "你猜的数字太小了\n",
      "请输入一个数字73\n",
      "你猜的数字太大了\n",
      "请输入一个数字71\n",
      "你猜的数字太小了\n",
      "请输入一个数字72\n",
      "恭喜你猜对啦\n"
     ]
    }
   ],
   "source": [
    "while True:\n",
    "    if count<10:\n",
    "        guess = input(\"请输入一个数字\")\n",
    "        guess_digit = int(guess)\n",
    "        if guess_digit>hide_hard:\n",
    "            print(\"你猜的数字太大了\")\n",
    "        elif guess_digit<hide_hard:\n",
    "            print(\"你猜的数字太小了\")\n",
    "        else:\n",
    "            print(\"恭喜你猜对啦\")\n",
    "    else:\n",
    "        print(\"游戏结束\")\n",
    "        break"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
